/* 1. run the command "ipcs" to check out the currently exited message queue
 * 2. use function msgctl(queueId, IPC_RMID, 0) to delete a msg_queue
 * run the command "ipcs -q queueId" to see the details
 * run the command "ipcrm -q queueId" to delete a msg_queue manually
 */


#include<iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <errno.h>
#include <sys/msg.h>
#include <sys/stat.h>

using namespace std;

const int BUFSIZE = 1023;
const char *MSG_FILE = "/";

struct MsgType
{
	long mtype;				/* message type, must be > 0 */
	char mtext[BUFSIZE+1];	/* message data */
};

int main()
{
//	msgctl(0, IPC_RMID, 0);
//	exit(0);

	struct MsgType msg;
	key_t key;
	int msgId;

	if ((key = ftok(MSG_FILE, 'a')) == -1)
	{
		cout << "Creat Key Error: " << strerror(errno) << endl;
		exit(1);
	}

	if((msgId = msgget(key, S_IRUSR|S_IWUSR|IPC_CREAT|IPC_EXCL)) == -1)
	{
		cout << "Creat Message Queue Error: " << strerror(errno) << endl;
		exit(1);
	}

	cout << "Messge ID: " << msgId << endl;

	while(1)
	{
		//if msgtyp = 0, receive the oldest msg from the msgQueue, no matter what msgtyp is
		msgrcv(msgId, &msg, sizeof(struct MsgType) - sizeof(long), 1, 0);
		cout << "Server recieve: " << msg.mtext << endl;
		msg.mtype = 2;
		msgsnd(msgId, &msg, sizeof(struct MsgType) - sizeof(long), 0);
	}

		msgctl(0, IPC_RMID, 0);
		exit(0);
	return 0;
}

